<template>
  <t-form
    v-if="step === 'forgot'"
    ref="form"
    class="item-container forgot-password-form"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <t-form-item name="usernameOrEmail">
      <t-input v-model="formData.usernameOrEmail" size="large" placeholder="请输入用户名或邮箱">
        <template #prefix-icon>
          <t-icon name="user" />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item>
      <t-button block size="large" type="submit">找回密码</t-button>
    </t-form-item>
    <div class="back-login">
      <t-link theme="primary" @click="backToLogin">返回登录</t-link>
    </div>
  </t-form>

  <t-form
    v-else
    ref="resetForm"
    class="item-container forgot-password-form"
    :data="resetFormData"
    :rules="RESET_FORM_RULES"
    label-width="0"
    @submit="onResetSubmit"
  >
    <t-form-item name="code">
      <t-input v-model="resetFormData.code" size="large" placeholder="请输入验证码">
        <template #prefix-icon>
          <t-icon name="security" />
        </template>
      </t-input>
      <template #help>
        <span v-if="lastCode">验证码：{{ lastCode }}</span>
      </template>
    </t-form-item>
    <t-form-item name="newPassword">
      <t-input v-model="resetFormData.newPassword" size="large" type="password" placeholder="请输入新密码">
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item name="confirmPassword">
      <t-input v-model="resetFormData.confirmPassword" size="large" type="password" placeholder="请再次输入新密码">
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item>
      <t-button block size="large" type="submit">重置密码</t-button>
    </t-form-item>
    <div class="back-login">
      <t-link theme="primary" @click="backToLogin">返回登录</t-link>
    </div>
  </t-form>

  <t-dialog v-model:visible="showEmailDialog" header="请输入注册时的邮箱" @confirm="onEmailDialogConfirm">
    <t-input v-model="emailInput" placeholder="请输入邮箱" style="margin-top: 12px; width: 100%;" />
  </t-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { MessagePlugin, FormRule } from 'tdesign-vue-next';
import { forgotPassword, resetPassword } from '@/api/user/index';
import type { ForgotPasswordParam, ResetPasswordParam } from '@/api/user/types';

const emit = defineEmits(['back']);

const step = ref<'forgot' | 'reset'>('forgot');
const lastUsernameOrEmail = ref('');
const lastCode = ref('');

const INITIAL_DATA: ForgotPasswordParam = {
  usernameOrEmail: '',
};
const FORM_RULES: Record<string, FormRule[]> = {
  usernameOrEmail: [
    { required: true, message: '用户名或邮箱必填', type: 'error' },
    { min: 4, message: '长度不能少于4位', type: 'error' },
  ],
};
const form = ref();
const formData = ref({ ...INITIAL_DATA });

const resetForm = ref();
const resetFormData = ref<ResetPasswordParam>({
  usernameOrEmail: '',
  code: '',
  newPassword: '',
  confirmPassword: '',
});
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,32}$/;
const RESET_FORM_RULES: Record<string, FormRule[]> = {
  code: [
    { required: true, message: '验证码必填', type: 'error' },
    { len: 6, message: '验证码为6位', type: 'error' },
  ],
  newPassword: [
    { required: true, message: '新密码必填', type: 'error' },
    { validator: val => passwordPattern.test(val), message: '密码8-32位，必须包含字母和数字', type: 'error' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', type: 'error' },
    {
      validator: (val: string) => val === resetFormData.value.newPassword,
      message: '两次输入的密码不一致',
      type: 'error',
    },
  ],
};

const emailPattern = /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
const showEmailDialog = ref(false);
const emailInput = ref('');
let pendingUsername = '';

const backToLogin = () => {
  emit('back');
};

const onSubmit = async ({ validateResult }: { validateResult: boolean }) => {
  if (validateResult === true) {
    const value = formData.value.usernameOrEmail.trim();
    if (emailPattern.test(value)) {
      await doForgotPassword(value);
    } else {
      pendingUsername = value;
      emailInput.value = '';
      showEmailDialog.value = true;
    }
  }
};

const onEmailDialogConfirm = async () => {
  if (!emailPattern.test(emailInput.value)) {
    MessagePlugin.error('请输入正确的邮箱格式');
    return false;
  }
  showEmailDialog.value = false;
  await doForgotPassword(emailInput.value);
};

const doForgotPassword = async (usernameOrEmail: string) => {
  try {
    const res = await forgotPassword({ usernameOrEmail });
    if (res.data && res.data.code === 200) {
      step.value = 'reset';
      lastUsernameOrEmail.value = usernameOrEmail;
      lastCode.value = res.data.message?.replace(/[^\d]/g, '') || '';
      resetFormData.value.usernameOrEmail = usernameOrEmail;
      resetFormData.value.code = lastCode.value;
      MessagePlugin.success('请填写验证码和新密码完成重置');
    } else {
      MessagePlugin.error(res.data?.message || '找回密码失败');
    }
  } catch (error) {
    MessagePlugin.error('找回密码异常，请稍后重试');
    console.error('[找回密码失败]', error);
  }
};

const onResetSubmit = async ({ validateResult }: { validateResult: boolean }) => {
  if (validateResult === true) {
    try {
      const params = { ...resetFormData.value };
      const res = await resetPassword(params);
      if (res.data && res.data.code === 200) {
        MessagePlugin.success('密码重置成功，请使用新密码登录！');
        emit('back');
      } else {
        MessagePlugin.error(res.data?.message || '重置密码失败');
      }
    } catch (error) {
      MessagePlugin.error('重置密码异常，请稍后重试');
      console.error('[重置密码失败]', error);
    }
  }
};
</script>

<style lang="less" scoped>
.forgot-password-form {
  margin-top: 24px;
}
.back-login {
  margin-top: 16px;
  text-align: right;
}
</style> 